package com.situ.crm2026.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.crm2026.model.Course;
import com.situ.crm2026.service.CourseService;
import com.situ.crm2026.service.UploadService;
import com.situ.crm2026.util.JsonResult;
import jakarta.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/v1/courses", produces = MediaType.APPLICATION_JSON_VALUE)
public class CourseApi {
    private CourseService courseService;
    private UploadService uploadService;

    @Autowired
    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }

    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Course csb) {
        try {
            Page<Course> page = new Page<>(pageNo, pageSize);
            page = this.courseService.findAll(page, csb);
            return ResponseEntity.ok(JsonResult.success(page));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(JsonResult.fail("查询课程信息失败: " + e.getMessage()));
        }
    }

    // 根据ID获取课程详情（包含会员信息）
    @GetMapping("/{id}")
    public ResponseEntity<JsonResult<?>> getCourseDetail(@PathVariable Integer id) {
        try {
            // 获取课程详情
            Course course = this.courseService.getCourseDetailById(id);
            if (course == null) {
                return ResponseEntity.ok(JsonResult.fail("课程不存在"));
            }

            // 获取预约该课程的会员列表
            List<Map<String, Object>> members = this.courseService.getMembersByCourseId(id);

            // 构造返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("id", course.getId());
            result.put("mcr_id", course.getMcrId());
            result.put("name", course.getName());
            result.put("coach", course.getCoach());
            result.put("room", course.getRoom());
            result.put("time", course.getStartTime());
            result.put("duration", course.getDuration());
            result.put("bookedCount", course.getBookedCount());
            result.put("maxCapacity", course.getMaxCapacity());
            result.put("avatar", course.getAvatar());
            result.put("members", members);

            return ResponseEntity.ok(JsonResult.success(result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(JsonResult.fail("查询课程详情失败: " + e.getMessage()));
        }
    }

    //批量删除
    @DeleteMapping
    public ResponseEntity<JsonResult<?>> deleteByIds(
            @RequestBody
            @Validated
            @Size(min = 1, message = "要删除的课程ID至少1个")
            Integer[] ids) {
        try {
            int count = this.courseService.deleteByIds(List.of(ids));
            if (count == 0) {
                return ResponseEntity.ok(JsonResult.fail("删除课程失败"));
            } else {
                return ResponseEntity.ok(JsonResult.success(count));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(JsonResult.fail("删除课程失败: " + e.getMessage()));
        }
    }

    //保存课程信息
    @PostMapping
    public ResponseEntity<JsonResult<?>> save(@RequestBody @Validated Course course) {
        try {
            boolean success = this.courseService.save(course);
            if (success) {
                return ResponseEntity.ok(JsonResult.success(course));
            } else {
                // 检查是否是因为时间教室冲突导致的失败
                if (this.courseService.hasTimeAndRoomConflict(course)) {
                    return ResponseEntity.ok(JsonResult.fail("课程时间和教室冲突"));
                }
                return ResponseEntity.ok(JsonResult.fail("保存课程失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains("课程时间和教室冲突")) {
                return ResponseEntity.ok(JsonResult.fail("课程时间和教室冲突"));
            }
            return ResponseEntity.status(500).body(JsonResult.fail("保存课程失败: " + e.getMessage()));
        }
    }

    //上传课程头像
    @PostMapping("/avatar")
    public ResponseEntity<JsonResult<?>> uploadCourseAvatar(MultipartFile file) {
        try {
            String path = this.uploadService.uploadImage(file, "course_avatar");
            return ResponseEntity.ok(JsonResult.success(path));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(JsonResult.fail("上传头像失败: " + e.getMessage()));
        }
    }

    //修改课程信息
    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody @Validated Course course) {
        try {
            boolean success = this.courseService.update(course);
            if (success) {
                return ResponseEntity.ok(JsonResult.success(course));
            } else {
                // 检查是否是因为时间教室冲突导致的失败
                if (this.courseService.hasTimeAndRoomConflict(course)) {
                    return ResponseEntity.ok(JsonResult.fail("课程时间和教室冲突"));
                }
                return ResponseEntity.ok(JsonResult.fail("修改课程失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains("课程时间和教室冲突")) {
                return ResponseEntity.ok(JsonResult.fail("课程时间和教室冲突"));
            }
            return ResponseEntity.status(500).body(JsonResult.fail("修改课程失败: " + e.getMessage()));
        }
    }
}
